package com.guang.springaoptransferdemo2.service.impl;


import com.guang.springaoptransferdemo2.domain.Account;
import com.guang.springaoptransferdemo2.domain.AccountExample;
import com.guang.springaoptransferdemo2.mapper.AccountMapper;
import com.guang.springaoptransferdemo2.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    private AccountMapper accountMapper;

//
//    @Autowired
//    private AccountServiceImpl accountService;

    @Override
    @Transactional
    public void transfer(String out, String in, Double money) {
        logger.info("先来进行查询用户余额，然后来进行增伤改操作");
        Account outAccount = findByName(out);
        Account inAccount = findByName(in);
        outAccount.setMoney(outAccount.getMoney() - money);
        inAccount.setMoney(inAccount.getMoney() + money);
        AccountServiceImpl accountService = (AccountServiceImpl) AopContext.currentProxy();
        logger.info("开始来进行增删改操作");
        accountService.edit(outAccount);
        // 没有出现异常！之前一切都是正常的
        int i = 1 / 0;
        accountService.edit(inAccount);

    }

    private Account findByName(String accountName) {
        AccountExample accountExample = new AccountExample();
        AccountExample.Criteria criteria = accountExample.createCriteria();
        criteria.andNameEqualTo(accountName);
        List<Account> accounts = accountMapper.selectByExample(accountExample);
        return CollectionUtils.firstElement(accounts);
    }

    @Transactional
    public int edit(Account account) {
        AccountExample accountExample = new AccountExample();
        AccountExample.Criteria criteria = accountExample.createCriteria();
        criteria.andIdEqualTo(account.getId());
        return accountMapper.updateByExampleSelective(account, accountExample);
    }

}